import { defineStore } from 'pinia';
import { Notification } from '@arco-design/web-vue';
import type { NotificationReturn } from '@arco-design/web-vue/es/notification/interface';
import type { RouteRecordNormalized } from 'vue-router';
import defaultSettings from '@/config/settings.json';
import { getMenuList } from '@/api/user';
import { AppState } from './types';
import { addDynamicRoutes } from '@/router';

const useAppStore = defineStore('app', {
  state: (): AppState => ({ ...defaultSettings }),

  getters: {
    appCurrentSetting(state: AppState): AppState {
      return { ...state };
    },
    appDevice(state: AppState) {
      return state.device;
    },
    appAsyncMenus(state: AppState): RouteRecordNormalized[] {
      return state.serverMenu as unknown as RouteRecordNormalized[];
    },
  },

  actions: {
    // Update app settings
    updateSettings(partial: Partial<AppState>) {
      // @ts-ignore-next-line
      this.$patch(partial);
    },

    // Change theme color
    toggleTheme(dark: boolean) {
      if (dark) {
        this.theme = 'dark';
        document.body.setAttribute('arco-theme', 'dark');
      } else {
        this.theme = 'light';
        document.body.removeAttribute('arco-theme');
      }
    },
    toggleDevice(device: string) {
      this.device = device;
    },
    toggleMenu(value: boolean) {
      this.hideMenu = value;
    },
    async fetchServerMenuConfig() {
      let notifyInstance: NotificationReturn | null = null;
      try {
        console.log('开始获取服务器菜单配置...');
        notifyInstance = Notification.info({
          id: 'menuNotice', // Keep the instance id the same
          content: '正在加载菜单数据...',
          closable: true,
        });
        const response = await getMenuList();
        console.log('获取到的原始响应:', response);

        // 处理不同的响应格式
        let menuData: any = null;
        const responseData: any = response.data;

        if (responseData) {
          // 格式1: { code: 200, data: [...], msg: 'success' }
          if (responseData.code === 200 && responseData.data) {
            menuData = responseData.data;
          }
          // 格式2: { data: [...], status: 'ok', msg: '请求成功', code: 20000 }
          else if (responseData.status === 'ok' && responseData.data) {
            menuData = responseData.data;
          }
          // 格式3: [...] (直接是数组)
          else if (Array.isArray(responseData)) {
            menuData = responseData;
          }
        }

        if (!menuData || (Array.isArray(menuData) && menuData.length === 0)) {
          console.warn('服务器返回的菜单数据为空或格式不正确，使用默认菜单');

          // 使用默认菜单
          menuData = this.getDefaultMenuData();

          notifyInstance = Notification.warning({
            id: 'menuNotice',
            content: '使用默认菜单',
            closable: true,
          });
        }

        console.log('处理后的菜单数据:', menuData);

        // 转换菜单数据格式，确保包含必要的字段
        const transformedMenu = this.transformMenuData(menuData);
        console.log('转换后的菜单数据:', transformedMenu);

        // 注册动态路由
        addDynamicRoutes(transformedMenu);

        this.serverMenu = transformedMenu;
        console.log('设置菜单数据完成:', this.serverMenu);

        notifyInstance = Notification.success({
          id: 'menuNotice',
          content: '菜单加载成功',
          closable: true,
        });
      } catch (error) {
        console.error('获取菜单数据失败，使用默认菜单:', error);

        // 使用默认菜单
        const defaultMenu = this.getDefaultMenuData();
        const transformedMenu = this.transformMenuData(defaultMenu);

        // 注册动态路由
        addDynamicRoutes(transformedMenu);

        this.serverMenu = transformedMenu;

        notifyInstance = Notification.error({
          id: 'menuNotice',
          content: '菜单加载失败，使用默认菜单',
          closable: true,
        });
      }
    },

    // 获取默认菜单数据
    getDefaultMenuData() {
      return [
        {
          path: '/dashboard',
          name: 'dashboard',
          component: 'Layout',
          meta: {
            locale: '仪表盘',
            requiresAuth: true,
            icon: 'icon-dashboard',
            order: 0,
          },
          children: [
            {
              path: 'workplace',
              name: 'Workplace',
              component: '/dashboard/workplace/index',
              meta: {
                locale: '工作台',
                requiresAuth: true,
                roles: ['*'],
              },
            },
            {
              path: 'monitor',
              name: 'Monitor',
              component: '/dashboard/monitor/index',
              meta: {
                locale: '监控页',
                requiresAuth: true,
                roles: ['admin'],
              },
            },
          ],
        },
        {
          path: '/system',
          name: 'system',
          component: 'Layout',
          meta: {
            locale: '系统管理',
            requiresAuth: true,
            icon: 'icon-settings',
            order: 1,
          },
          children: [
            {
              path: 'menu',
              name: 'Menu',
              component: '/system/menu/index',
              meta: {
                locale: '菜单管理',
                requiresAuth: true,
                roles: ['admin'],
              },
            },
          ],
        },
      ];
    },

    // 转换菜单数据格式
    transformMenuData(menuData: any[]): RouteRecordNormalized[] {
      return menuData.map((item) => {
        // 构建基本路由对象
        const route: any = {
          path: item.path || '',
          name: item.name || '',
          meta: {
            locale: item.meta?.locale || item.name || '',
            requiresAuth: true,
            icon: item.meta?.icon || item.icon || '',
            order: item.meta?.order || item.orderNum || 0,
            hideInMenu: item.meta?.hideInMenu || item.isHidden === 1,
            roles: item.meta?.roles || ['*'],
          },
        };

        // 添加组件信息
        if (item.component) {
          // 处理特殊的组件名称
          if (
            item.component === 'default-layout' ||
            item.component === 'Layout'
          ) {
            route.component = 'Layout';
          } else {
            // 保留原始组件路径，由 addDynamicRoutes 处理
            route.component = item.component;
          }
        } else if (!item.children || item.children.length === 0) {
          // 叶子节点，需要有组件
          const pathParts = item.path.split('/').filter(Boolean);
          if (pathParts.length >= 2) {
            route.component = `${pathParts.join('/')}/index`;
          }
        } else {
          // 父节点默认使用Layout
          route.component = 'Layout';
        }

        // 处理重定向
        if (item.redirect) {
          route.redirect = item.redirect;
        }

        // 处理子菜单
        if (item.children && item.children.length > 0) {
          route.children = this.transformMenuData(item.children);
        }

        console.log('转换菜单项:', {
          原始数据: {
            path: item.path,
            name: item.name,
            component: item.component,
            redirect: item.redirect,
          },
          转换后: {
            path: route.path,
            name: route.name,
            component: route.component,
            redirect: route.redirect,
          },
        });

        return route;
      });
    },
    clearServerMenu() {
      this.serverMenu = [];
    },
  },
});

export default useAppStore;
